package com.logicwin.RobotTravel.Navigate;

import java.io.FileDescriptor;
import java.util.LinkedList;
import java.util.List;

import com.logicwin.RobotTravel.Screens.ScreenNavigate;
import com.logicwin.RobotTravel.Services.Impl.ServiceManager;
import com.logicwin.RobotTravel.Navigate.messages.*;
import com.logicwin.RobotTravel.Position.Position;

import android.content.Context;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;

public class ScreenNavigateImpl {
	private final static String TAG = ScreenNavigateImpl.class.getCanonicalName();
	private WifiManager mWifi;	
	private WifiScanReceiver mReceiver;
	private MediaPlayer mMP;	
	private ScreenNavigate mScreenNavigate;
	private boolean mbActive;
	private final String nullSound = "/sdcard/4.mp3";
	LinkedList<BaseEvent> mEvents;
	private String mCurMac;
	public ScreenNavigateImpl(ScreenNavigate screenNavigate){
		mScreenNavigate = screenNavigate;
        mMP = new MediaPlayer();	
        mEvents = new LinkedList<BaseEvent>();
	}
	
	public void setupWifi() {
		mWifi = (WifiManager) mScreenNavigate.getSystemService(Context.WIFI_SERVICE);
		if(!mWifi.isWifiEnabled()){
			mWifi.setWifiEnabled(true);
		}
		// Get WiFi status
		WifiInfo info = mWifi.getConnectionInfo();
		// textStatus.append("\n\nWiFi Status: " + info.toString());
		Log.i(TAG, "WiFi Status: " + info.toString());
		// List available networks
		List<WifiConfiguration> configs = mWifi.getConfiguredNetworks();
		for (WifiConfiguration config : configs) {
			//textStatus.append("\n\n" + config.toString());
			Log.i(TAG, "WiFi configuration: " + config.toString());
		}
		
		// Register Broadcast Receiver
		if (mReceiver == null)
			mReceiver = new WifiScanReceiver(this);
		
		mScreenNavigate.registerReceiver(mReceiver, new IntentFilter(
				WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));		 
		//wifi.startScan();
	}
	public void unRegWifi(){
		mScreenNavigate.unregisterReceiver(mReceiver);
	}
	public void ScanWifi(){
		mWifi.startScan();
	}
	public WifiManager getWifiManager(){
		return mWifi;
	}
	public void StrongestWifiSignalFind(String macAddress){
		
		Bundle bundle = new Bundle();
		Message msg = null;
		if(macAddress == null){
			bundle.putString("audioname", nullSound);
			msg = new MessageNoWifi().getMsg();
			
			
		}	
		else if(ServiceManager.getPositoinService().getCurPosition() == null ||
				macAddress.equals(ServiceManager.getPositoinService().getCurPosition().getMacAddress()) == false){
			Position position = ServiceManager.getPositoinService().findPosition(macAddress);
			if(position == null){
				Log.e(TAG, "unknown mac address "+macAddress);				
				return;
			}
			ServiceManager.getPositoinService().setCurrPosition(position);
			bundle.putString("viewname",position.getText());
			bundle.putString("audioname", position.getAudio());
			bundle.putInt("audioid", position.getAudioId());
			msg = new MessageWifiChange().getMsg();					
		}
		else{
			bundle.putString("audioname", ServiceManager.getPositoinService().getCurPosition().getAudio());
			bundle.putInt("audioid", ServiceManager.getPositoinService().getCurPosition().getAudioId());
			msg = new MessageWifiNoChange().getMsg();				
		}
		/*
		else if(macAddress.equals(ServiceManager.getPositoinService().getCurPosition().getMacAddress())){			
			bundle.putString("audioname", ServiceManager.getPositoinService().getCurPosition().getAudio());
			msg = new MessageWifiNoChange().getMsg();		
		}
		else{
			Position position = ServiceManager.getPositoinService().findPosition(macAddress);
			if(position == null){
				Log.e(TAG, "unknown mac address "+macAddress);				
				return;
			}
			bundle.putString("audioname", position.getAudio());
			msg = new MessageWifiChange().getMsg();				
			//mScreenNavigate.getHandler().sendMessage(new MessageWifiChange().getMsg());
		}
		*/
		msg.setData(bundle);
		mScreenNavigate.getHandler().sendMessage(msg);
	}
	
	public int getEventQueueSize(){
		return mEvents.size();
	}
	public void postEvent(BaseEvent event){
		synchronized (mEvents){
			mEvents.addLast(event);
		}
	}
	
	public void clearPositionInfo(){
		ServiceManager.getPositoinService().setCurrPosition(null);
	}
	public BaseEvent getEvent(){
		synchronized (mEvents){
			if(mEvents.size() == 0) return null;
			
			BaseEvent event= mEvents.getFirst();
			mEvents.remove();
			return event;
		}				
	}
	public void playMusic(int resid){
		try{
			AssetFileDescriptor afd = mScreenNavigate.getResources().openRawResourceFd(resid);
			mMP.reset();
			mMP.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
			afd.close();
 			mMP.prepare();
 			mMP.start();			
		}catch (Exception e) {
  			// TODO: handle exception
  			e.printStackTrace();
  		}
		
	}
    public void playMusic(String path){
  	   try { 
  		 
 			mMP.reset();
 			mMP.setDataSource(path);
 			mMP.prepare();
 			mMP.start();
  		} catch (Exception e) {
  			// TODO: handle exception
  			e.printStackTrace();
  		}
  	}
    public void stopPlayMusic(){
    	try{
    		if(mMP.isPlaying()){
    			mMP.stop();
    		}
    	}
    	catch(Exception e){
    		
    	}
    }
    public boolean getActive(){
    	return mbActive;
    }
    public void setActive(boolean flag){
    	mbActive = flag;
    }
}
